package com.example.service.impl;

import cn.hutool.core.date.DateUtil;
import com.example.entity.Phone;
import com.example.mapper.PhoneMapper;
import com.example.mapper.VersionMapper;
import com.example.service.PhoneService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 手机设备Service实现类
 */
@Service
public class PhoneServiceImpl implements PhoneService {

    @Resource
    private PhoneMapper phoneMapper;
    
    @Resource
    private VersionMapper versionMapper;

    /**
     * 分页查询手机设备
     */
    @Override
    public PageInfo<Phone> page(Integer pageNum, Integer pageSize, String name, String model) {
        PageHelper.startPage(pageNum, pageSize);
        List<Phone> list = phoneMapper.list(name, model);
        return new PageInfo<>(list);
    }

    /**
     * 根据ID查询手机设备
     */
    @Override
    public Phone getById(Integer id) {
        return phoneMapper.getById(id);
    }

    /**
     * 新增手机设备
     */
    @Override
    public void add(Phone phone) {
        // 初始化固件数量为0
        phone.setFirmwareCount(0);
        phone.setCreateTime(DateUtil.now());
        phoneMapper.insert(phone);
    }

    /**
     * 更新手机设备
     */
    @Override
    public void update(Phone phone) {
        phoneMapper.update(phone);
    }

    /**
     * 删除手机设备
     */
    @Override
    @Transactional
    public void delete(Integer id) {
        // 先删除关联的固件版本
        versionMapper.deleteByPhoneId(id);
        // 再删除手机设备
        phoneMapper.deleteById(id);
    }
} 